package com.twohand.admin.Aop;

import com.twohand.admin.Annotation.Permission;
import com.twohand.admin.Entity.User;
import com.twohand.admin.Interceptor.Request;
import com.twohand.admin.Service.MenuService;
import com.twohand.admin.Util.JwtUtil;
import com.twohand.utils.Response.BaseException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

@Aspect
@Component
public class PermissionAop {
    @Autowired
    MenuService menuService;
    Logger log = LoggerFactory.getLogger(PermissionAop.class);

    @Pointcut("@annotation(com.twohand.admin.Annotation.Permission)")
    public void verifyPermission(){

    }

    @Before("verifyPermission()")
    public void checkBefore(JoinPoint joinPoint){
        System.out.println("走注解"+joinPoint);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method =signature.getMethod();
        Permission annotation = method.getAnnotation(Permission.class);
        String need = annotation.value();
        User user = JwtUtil.getCurrentUser();
        List<String> permissions =  menuService.getPermissionByUserId(user.getId());
        if(need!=null || !need.equals("")){
            if(!permissions.contains(need)){
                log.info("userId:"+user.getId()+",没有"+need+"权限");
                throw new BaseException(403,"没有操作权限，请联系管理员");
            }
        }

    }
}
